<script setup>
import { ref, reactive } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

// 登录状态
const loading = ref(false)

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 表单校验规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
})

// 表单引用
const loginFormRef = ref(null)

// 登录提交函数
const submitForm = async (formEl) => {
  if (!formEl) return
  
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      try {
        const res = await userStore.login(loginForm)
        if (res.code === 0 || res.code === 200) {
          // 登录成功后同步获取用户信息
          await userStore.fetchUserInfo()
          ElMessage.success('登录成功')
          
          // 根据用户角色跳转到不同页面
          const userInfo = userStore.userInfo
          const userRole = userInfo.roles?.[0] // 获取用户角色
          
          if (userRole === 'ADMIN' || userRole === 'TEACHER') {
            // 管理员或教师跳转到教师后台
            router.push('/teacher')
          } else if (userRole === 'STUDENT') {
            // 学生跳转到首页
            router.push('/')
          } else {
            // 其他情况跳转到首页
            router.push('/')
          }
        }
      } catch (error) {
        console.error('登录错误:', error)
        ElMessage.error(error.message || '登录失败，请稍后重试')
      } finally {
        loading.value = false
      }
    } else {
      console.log('验证失败', fields)
      ElMessage.error('请检查表单填写是否正确')
    }
  })
}

// 返回首页
const goBack = () => {
  router.push('/')
}

// 点击忘记密码
const goToForgotPassword = () => {
  router.push('/forgot-password')
}

// 点击注册
const goToRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h2 class="login-title">用户登录</h2>
        <p class="login-subtitle">欢迎回来，请登录您的账号</p>
      </div>
      
      <el-form 
        ref="loginFormRef"
        :model="loginForm" 
        :rules="rules" 
        label-position="top"
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名"
          >
            <template #prefix>
              <el-icon><user /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
            @keyup.enter="submitForm(loginFormRef)"
          >
            <template #prefix>
              <el-icon><lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <div class="form-options">
          <el-checkbox>记住我</el-checkbox>
          <el-link type="primary" @click="goToForgotPassword">忘记密码?</el-link>
        </div>
        
        <el-form-item>
          <el-button 
            type="primary" 
            class="login-btn"
            @click="submitForm(loginFormRef)"
            :loading="loading"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
        
        <div class="register-link">
          <span>没有账号? </span>
          <el-link type="primary" @click="goToRegister">立即注册</el-link>
        </div>
        
        <div class="back-link">
          <el-link @click="goBack">返回首页</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4ebf5 100%);
  font-family: 'Inter', 'Source Sans Pro', 'Microsoft YaHei', sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-card {
  width: 400px;
  max-width: 90%;
  padding: 40px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(229, 231, 235, 0.7);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-title {
  font-size: 28px;
  font-weight: 700;
  color: #2c5dff;
  margin-bottom: 10px;
}

.login-subtitle {
  font-size: 15px;
  color: #6b7280;
}

.login-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-footer {
  margin-top: 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.login-btn {
  width: 100%;
  padding: 12px 20px;
  background: linear-gradient(135deg, #2c5dff 0%, #0097ff 100%);
  border: none;
  border-radius: 8px;
  color: white;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  box-shadow: 0 5px 15px rgba(44, 93, 255, 0.2);
  transition: all 0.3s;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(44, 93, 255, 0.3);
}

.login-btn:disabled {
  background: #94a3b8;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.login-links {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
}

.login-links a {
  color: #2c5dff;
  text-decoration: none;
  margin: 0 10px;
  transition: color 0.2s;
}

.login-links a:hover {
  color: #1c4de0;
  text-decoration: underline;
}

.social-login {
  margin-top: 30px;
  text-align: center;
}

.social-login-title {
  position: relative;
  margin-bottom: 20px;
  font-size: 14px;
  color: #6b7280;
}

.social-login-title::before,
.social-login-title::after {
  content: "";
  position: absolute;
  top: 50%;
  width: 80px;
  height: 1px;
  background: #e6e6e6;
}

.social-login-title::before {
  left: 0;
}

.social-login-title::after {
  right: 0;
}

.social-login-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.social-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8faff;
  border: 1px solid rgba(44, 93, 255, 0.1);
  cursor: pointer;
  transition: all 0.2s;
}

.social-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(44, 93, 255, 0.1);
  background: #f0f5ff;
}

.social-btn i {
  font-size: 20px;
  color: #2c5dff;
}

:deep(.el-input__inner) {
  border-radius: 8px;
}

:deep(.el-input__inner:focus) {
  border-color: #2c5dff;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #2c5dff;
  border-color: #2c5dff;
}

:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #2c5dff;
}
</style> 